<template lang="pug">
.list
  el-tabs(v-model="activeName" @tab-click="handleClick")
    el-tab-pane(label="案例轮播图" name="first")
      .el-image-info 提示：最多设置5个案例，支持拖动图片更换顺序
      .material-section
        draggable(:list="caseList" filter=".openCase" @update="onUpdateCase")
          transition-group(class="material-image-bd")
            .material-image-item(class="cursor" v-for="(item, index) in caseList" :key="index")
              .material-image-relative
                i(class="el-icon-circle-close" @click.stop="delCase(item, 0)")
                img(:src="item.url" style="width:320px; height:200px")
              .material-side-bd
                .material-image-name {{ item.projectName }}
                .material-image-publisher {{ item.designOwner }}
            .material-image-item(class="openCase" key="addCase")
              .el-case-btn(@click="openCaseDialog")
                .iconfont.icon-tianjia
                .add-case-btn-txt 添加案例
    el-tab-pane(label="材料轮播图" name="second")
      .el-image-info 提示：最多设置5个材料，支持拖动图片更换顺序
      .material-section
        draggable(:list="materialList" filter=".openMaterial" @update="onUpdateMaterial")
          transition-group(class="material-image-bd")
            .material-image-item(class="cursor" v-for="(item, index) in materialList" :key="index")
              .material-image-relative
                i(class="el-icon-circle-close" @click.stop="delMaterial(item)")
                img(:src="item.picImg" style="width:320px; height:200px")
              .material-side-bd
                .material-image-name {{ item.materialName }}
                .material-image-publisher {{ item.brandName }}
                .material-image-publisher {{ item.supplierName }}
            .material-image-item(class="openMaterial" key="addMaterial")
              .el-case-btn(@click="openMaterialDialog")
                .iconfont.icon-tianjia
                .add-case-btn-txt 添加材料
    el-tab-pane(label="热门视频案例设置" name="third")
      .el-image-info 提示：最多设置5个视频案例，支持拖动图片更换顺序
      .material-section
        draggable(:list="videoCaseList" filter=".openVideoCase" @update="onUpdateVideoCase")
          transition-group(class="material-image-bd")
            .material-image-item(class="cursor" v-for="(item, index) in videoCaseList" :key="index")
              .material-image-relative
                i(class="el-icon-circle-close" @click.stop="delCase(item, 1)")
                img(:src="item.url" style="width:320px; height:200px")
              .material-side-bd
                .material-image-name {{ item.projectName }}
                .material-image-publisher {{ item.designOwner }}
            .material-image-item(class="openVideoCase" key="addVideoCase")
              .el-case-btn(@click="openVideoCaseDialog")
                .iconfont.icon-tianjia
                .add-case-btn-txt 添加视频案例
  add-case-dialog(
    type="0"
    :show="showCaseDialog"
    @close="closeCaseDialog"
  )
  add-material-dialog(
    :show="showMaterialDialog"
    @close="closeMaterialDialog"
  )
  add-case-dialog(
    type="1"
    :show="showVideoCaseDialog"
    @close="closeVideoCaseDialog"
  )
</template>

<script>
import draggable from 'vuedraggable'
import { getHotCases, setHotCases, changeHotCaseOrder, getHotMaterials, changeHotMaterialOrder, setHotMaterials } from 'api'
import addCaseDialog from '@/components/modal/addCaseDialog'
import addMaterialDialog from '@/components/modal/addMaterialDialog'
export default {
  name: 'homeRecManage',
  data () {
    return {
      showCaseDialog: false,
      showMaterialDialog: false,
      showVideoCaseDialog: false,
      activeName: 'first',
      caseList: [],
      materialList: [],
      videoCaseList: []
    }
  },
  components: {
    draggable,
    addCaseDialog,
    addMaterialDialog
  },
  methods: {
    async getHotCaseList () {
      try {
        const { ResultSet } = await this.$axios.post(getHotCases, { type: 0 })
        this.caseList = ResultSet.userData.setList || []
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getHotMaterialList () {
      try {
        const { ResultSet } = await this.$axios.post(getHotMaterials)
        this.materialList = ResultSet.userData.setList || []
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getHotVideoCaseList () {
      try {
        const { ResultSet } = await this.$axios.post(getHotCases, { type: 1 })
        this.videoCaseList = (ResultSet.userData.setList || []).map(item => {
          // const urlImg = await this.getVideoBase64(item.url)
          // item.url = urlImg
          this.getVideoBase64(item.url).then(url => {
            item.url = url
          })
          return item
        })
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    init () {
      this.getHotCaseList()
    },
    handleClick (tab, event) {
      if('first' === tab.name) {
        this.getHotCaseList()
      } else if ('second' === tab.name) {
        this.getHotMaterialList()
      } else if ('third' === tab.name) {
        this.getHotVideoCaseList()
      }
    },
    getVideoBase64 (url) {
      //获取视频第一帧图片
      return new Promise((resolve, reject) => {
        try {
          let dataURL = ''
          let video = document.createElement("video")
          video.setAttribute('crossOrigin', 'anonymous') //处理跨域
          video.setAttribute('src', url)
          video.setAttribute('preload', 'auto')
          video.currentTime = 1
          video.addEventListener('loadeddata', () => {
            let canvas = document.createElement("canvas")
            const width = video.videoWidth || 320
            const height = video.videoHeight || 200
            canvas.width = width //canvas的尺寸和图片一样
            canvas.height = height
            canvas.getContext("2d").drawImage(video, 0, 0, width, height) //绘制canvas
            dataURL = canvas.toDataURL('image/jpeg') //转换为base64
            resolve(dataURL)
          })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    async onUpdateCase (e) {
      //拖拽排序发生变化时
      try {
        let query = {
          caseIdsList: this.caseList.map(item => item.materialCaseId).join(',')
        }
        await this.$axios.post(changeHotCaseOrder, { ...query })
        this.$message.success('图片更换顺序成功！')
        this.getHotCaseList()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async onUpdateMaterial (e) {
      //拖拽排序发生变化时
      try {
        let query = {
          materialIdsList: this.materialList.map(item => item.id).join(',')
        }
        await this.$axios.post(changeHotMaterialOrder, { ...query })
        this.$message.success('图片更换顺序成功！')
        this.getHotMaterialList()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async onUpdateVideoCase (e) {
      //拖拽排序发生变化时
      try {
        let query = {
          caseIdsList: this.videoCaseList.map(item => item.materialCaseId).join(',')
        }
        await this.$axios.post(changeHotCaseOrder, { ...query })
        this.$message.success('图片更换顺序成功！')
        this.getHotVideoCaseList()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    delCase (item, type) {
      this.$confirm('是否确定删除该案例设置？', '取消提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //取消热门案例
        try {
          let query = {
            type: type,
            materialCaseId: item.materialCaseId
          }
          await this.$axios.post(setHotCases, { ...query })
          this.$message.success('删除成功！')
          if(type === 0) {
            this.getHotCaseList()
          } else {
            this.getHotVideoCaseList()
          }
        } catch (err) {
          console.log(err)
          this.$message.error(err.message || err.ResultSet.errors)
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    delMaterial (item) {
      this.$confirm('是否确定删除该材料设置？', '取消提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //取消热门材料
        try {
          let query = {
            materialId: item.id
          }
          await this.$axios.post(setHotMaterials, { ...query })
          this.$message.success('删除成功！')
          this.getHotMaterialList()
        } catch (err) {
          console.log(err)
          this.$message.error(err.message || err.ResultSet.errors)
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    openCaseDialog () {
      this.showCaseDialog = true
    },
    closeCaseDialog () {
      this.showCaseDialog = false
      this.getHotCaseList()
    },
    openMaterialDialog () {
      this.showMaterialDialog = true
    },
    closeMaterialDialog () {
      this.showMaterialDialog = false
      this.getHotMaterialList()
    },
    openVideoCaseDialog () {
      this.showVideoCaseDialog = true
    },
    closeVideoCaseDialog () {
      this.showVideoCaseDialog = false
      this.getHotVideoCaseList()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.init()
    })
  }
}
</script>

<style lang="scss">
.el-tabs__nav {
  .el-tabs__item {
    font-size: 16px;
    line-height: 48px;
    height: 48px;
  }
}
</style>
<style lang="scss" scoped>
.list {
  width: 100%;
  min-height: 100%;
  background: #FFFFFF;
  border: 1px solid #F3F3F4;
  box-sizing: border-box;
  box-shadow: 0px 4px 0px #F3F3F4;
  border-radius: 10px;
  padding: 0 40px;
}
.material-section {
  padding: 16px 0;
  display: flex;
}

.el-image-info {
  font-size: 14px;
  line-height: 24px;
  color: #AFAFAF;
}
.material-image-bd {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}
.material-image-item {
  margin-right: 36px;
  margin-bottom: 36px;
  .material-image-relative {
    position: relative;
  }
  &.cursor {
    cursor: pointer;
  }
  .material-side-bd {
    margin-top: 10px;
    .material-image-name {
      width: 320px;
      font-size: 14px;
      line-height: 20px;
      font-weight: bold;
      color: #3E4373;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2; //行数
      -webkit-box-orient: vertical;
    }
    .material-image-publisher {
      width: 320px;
      font-size: 12px;
      line-height: 20px;
      color: #AFAFAF;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.el-icon-circle-close {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 1;
  font-size: 20px;
  color: #EE0A24;
  cursor: pointer;
}
.el-case-btn {
  width: 320px;
  height: 200px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #B2B4C7;
  border: 1px solid #c0ccda;
  cursor: pointer;
  &:hover {
    border-color: #FF708B;
    color: #FF708B;
  }
  .iconfont {
    font-size: 20px;
    font-weight: bold;
  }
  .add-case-btn-txt {
    font-size: 14px;
  }
}
</style>
